package com.elinkway.infinitemovies.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.ChannelAdapter;
import com.elinkway.infinitemovies.adapter.ChannelHomeListAdapter;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.Channel;
import com.elinkway.infinitemovies.bean.ChannelInfo;
import com.elinkway.infinitemovies.bean.ChannelInfoList;
import com.elinkway.infinitemovies.bean.ChannelNewParams;
import com.elinkway.infinitemovies.bean.ChannelPiece;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.http.requesttask.RequestPieceTask;
import com.elinkway.infinitemovies.ui.activity.ChannelDetailActivity;
import com.elinkway.infinitemovies.ui.activity.LiveActivity;
import com.elinkway.infinitemovies.ui.activity.LoginActivity;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.view.NoScrollListView;
import com.elinkway.infinitemovies.view.PublicLoadLayout;
import com.le123.ysdq.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;
import java.util.Map;

public class ChannelFragment extends BaseFragment implements
        ListView.OnItemClickListener, OnClickListener {
    public static final String TAG = "NewChannelFragment";

    private final String VARIETY = "综艺";

    private final String MOVIES = "电影";

    private final String CARTOON = "动漫";

    private final String TV_PLAY = "电视剧";

    private final String RECORD = "纪录片";

    private boolean isCurPage;

    /**
     * The fragment's ListView/GridView.
     */
    private NoScrollListView mListView;

    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private ChannelHomeListAdapter mAdapter;

    private PublicLoadLayout root;
    private ChannelInfoList channels;

    private List<ChannelPiece> mChannelPiece;

    private RequestPieceTask requestPieceTask;

    private LinearLayout mLinearLayout;

    private LayoutInflater mInflater;

    private RequestPieceListener mPieceRequsetListener;

    private SharedPreferences mLoginSp;

    public static ChannelFragment newInstance(int position) {
        ChannelFragment fragment = new ChannelFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ChannelFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");

        root = UIs.createPage(getActivity(), R.layout.fragment_channel);
        root.loading(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView");
        mLinearLayout = (LinearLayout) root.findViewById(R.id.channel_layout_ll);
        mInflater = LayoutInflater.from(getActivity());
        mLoginSp = getActivity().getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        // Set the adapter

        mListView = (NoScrollListView) root
                .findViewById(R.id.channel_home_list);
        mAdapter = new ChannelHomeListAdapter(getActivity()
                .getApplicationContext());
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(this);

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        mPieceRequsetListener = new RequestPieceListener();

        startChannelPieceRequest();

        return root;
    }

    public void startChannelPieceRequest() {
        if (requestPieceTask != null && !requestPieceTask.isCancelled()) {
            requestPieceTask.cancel();
        }
        requestPieceTask = null;
        requestPieceTask = new RequestPieceTask(getActivity());
        requestPieceTask.setOnListener(mPieceRequsetListener);
        requestPieceTask.start();
    }

    private class RequestPieceListener implements RequestResultListener<Channel> {

        @Override
        public boolean onRequestFailed() {
            root.error(false, false);
            root.setmRefreshData(new PublicLoadLayout.RefreshData() {

                @Override
                public void refreshData() {
                    if (requestPieceTask != null) {
                        if (!requestPieceTask.isCancelled()) {
                            requestPieceTask.cancel();
                        }
                    }
                    requestPieceTask = new RequestPieceTask(getActivity());
                    requestPieceTask.setOnListener(mPieceRequsetListener);
                    requestPieceTask.start();
                }
            });
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, Channel result) {
            mChannelPiece = result.getChannel();
            initChannelView(result);
        }

        @Override
        public void onPreRequest() {

        }
    }

    private void initChannelView(Channel result) {
        root.finish();
        if (result == null){
            return;
        }
        for (int i = 0; i < mChannelPiece.size(); i++) {
            LogUtils.e(TAG, "result " + mChannelPiece.size() + " " + mChannelPiece.get(i).getName());
            View linearLayout = mInflater.inflate(R.layout.channel_grid, null);
            RelativeLayout channelRelative = (RelativeLayout) linearLayout.findViewById(R.id.rl_channel);
            TextView channelTextView = (TextView) linearLayout.findViewById(R.id.tv_channel_text);
            TextView channelTextMore = (TextView) linearLayout.findViewById(R.id.tv_channel_more);
            ImageView channelImageView = (ImageView) linearLayout.findViewById(R.id.iv_channel_icon);
            GridView gridView = (GridView) linearLayout.findViewById(R.id.gv_channel_fragment);
            channelTextView.setText(mChannelPiece.get(i).getName());
            final int vt;
            final int temp = i;
            if (!TextUtils.isEmpty(mChannelPiece.get(i).getVt()) && (vt = Integer.parseInt(mChannelPiece.get(i).getVt())) > 0) {
                channelTextMore.setVisibility(View.VISIBLE);
                channelRelative.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (vt > 0) {
                            Map<String, String> dataMap = BigDataApi.createDataMap("0", "channel=" + mChannelPiece.get(temp).getName()
                                    +"&subchannel=more","0","-","","-");
                            dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_CATEGORY);
                            if (mLoginSp != null) {
                                dataMap.put("uid", mLoginSp.getString(LoginActivity.UID, ""));
                            }
                            dataMap.put("ilu", mLoginSp == null || TextUtils.isEmpty(mLoginSp.getString(LoginActivity.UID, "")) ? "0" : "1");
                            BigDataApi.bigDataCommonReport(dataMap, getActivity());
                            ChannelNewParams channelNewParams = new ChannelNewParams();
                            channelNewParams.setName(mChannelPiece.get(temp).getName());
                            ChannelDetailActivity.launch(getActivity(), mChannelPiece.get(temp).getVt(),
                                    mChannelPiece.get(temp).getName(), channelNewParams);
                        }
                    }
                });
            } else {
                channelTextMore.setVisibility(View.GONE);
            }

            if(!TextUtils.isEmpty(mChannelPiece.get(i).getPic())){
                ImageLoader.getInstance().displayImage(mChannelPiece.get(i).getPic(), channelImageView);
            }
            ChannelAdapter gridAdapter = new ChannelAdapter(getActivity(), mChannelPiece.get(i).getChannelNewBeanList());
            gridView.setAdapter(gridAdapter);
            if (mChannelPiece.get(i).getChannelNewBeanList() == null
                    || mChannelPiece.get(i).getChannelNewBeanList().size() <= 0) {
                gridView.setVisibility(View.GONE);
            }
            gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
            mLinearLayout.addView(linearLayout);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.i(TAG, "onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "onDetach");
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        ChannelInfo channel = channels.getChannels().get(position);
        if (channel.getVt().equals(MoviesConstant.VT_LIVE)) {
            UmengEventPoster.postChannelClick(channel.getName());
            Intent i = new Intent(getActivity(), LiveActivity.class);
            startActivity(i);
        } else {
            LogUtils.i(TAG, "channel's name is " + channel.getName());
            if (VARIETY.equals(channel.getName())) {
                UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_VARIETY, TAG);
            } else if (MOVIES.equals(channel.getName())) {
                UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_MOVIES, TAG);
            } else if (CARTOON.equals(channel.getName())) {
                UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_CARTOON, TAG);
            } else if (TV_PLAY.equals(channel.getName())) {
                UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_TV_PALY, TAG);
            } else if (RECORD.equals(channel.getName())) {
                UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_RECORD, TAG);
            }
            ChannelDetailActivity.launch(getActivity(), channel.getVt(),
                    channel.getName(), null);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isCurPage = true;
            Log.i(TAG, "onDisplay?");
            LogUtils.e(TAG, "on reResume request addata !!!!prepare!!!!");
            // 相当于Fragment的onResume
        } else {
            isCurPage = false;
            // 相当于Fragment的onPause
        }
    }

}
